﻿@inject IHttpService _httpService


@inject NavigationManager NavigationManager
@inject IJSRuntime JS
@inject IDataCacheService _dataCatcheService

@implements IDisposable

@if (string.IsNullOrWhiteSpace(Model.DisplayName) == false)
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip Title="@(Model.DisplayName)" Description="@Model.BriefIntroduction" Image="@Model.MainPicture" />
}
else
{
    <CnGalWebSite.Shared.MasaComponent.Shared.Cards.TitleTip />
}
@if (_dataCatcheService.ThemeSetting.IsTransparent)
{
    @if (string.IsNullOrWhiteSpace(Model.SmallBackgroundPicture) == false)
    {
        <div id="web_bg" style="background-image: url(@Model.SmallBackgroundPicture)" class=" d-none  bg-d-lg-block bgimage-ison"></div>
    }
    @if (string.IsNullOrWhiteSpace(Model.BackgroundPicture) == false)
    {
        <div id="web_bg" style="background-image: url(@Model.BackgroundPicture)" class=" d-none d-sm-block bgimage-ison"></div>
    }

}



@if (isNotFound == true)
{
    <NotFoundCard>
        <h1 class="text-center title-large">找不到这个投票哦......</h1>
        <div class="text-center">如果链接没有错的话，可以试试联系管理员</div>
    </NotFoundCard>
}
else
{
    @if (_dataCatcheService.VoteIndexPageCatche.Check(Id) || isReady)
    {
        @if (Model.IsHidden == true)
        {
            <CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaAlert Type="AlertTypes.Warning" Class="mb-3">
                当前投票处于隐藏状态，如果你看到了这个提示，请立即联系管理员
            </CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaAlert>
        }
        <MDCard Outline>
         <div>
             <CnGalWebSite.Shared.Component.Votes.MainPage.MainInforCard Model="Model" />
         </div>
         <AuthorizeView Roles="Admin">
             <Authorized>
                 <div class="ms-3 me-3 mt-3">
                     <CnGalWebSite.Shared.Component.Votes.MainPage.ExtraButtonCard Model="Model" StateChanged="HiddenStateChanged" />
                 </div>
             </Authorized>
         </AuthorizeView>

        </MDCard>
                <CnGalWebSite.Shared.Component.Votes.MainPage.OptionsInforCard Model="Model" IsShowResult="Model.ShowResult" />
            @if (Model.ShowResult == false || Model.IsAllowModification)
            {
                <MDCard Class="mb-4">
                    <CnGalWebSite.Shared.Component.Votes.MainPage.VoteButtonCard Model="Model" OnVoted="OnVoted" OnReVoted="OnReVoted" />
                </MDCard>
            }
        @if (Model.Users.Count != 0)
        {
            <CnGalWebSite.Shared.Component.Votes.MainPage.ListUserInforCard Model="Model" />
        }
        @if (Model.Entries.Count != 0 || Model.Artciles.Count != 0 || Model.Peripheries.Count != 0)
        {
            <CnGalWebSite.Shared.Component.Votes.MainPage.RelevanceInforCard Model="Model" />
        }


        <CnGalWebSite.Shared.MasaComponent.PC.Comments.CommentTip CanComment="Model.CanComment" CanDeleted="IsAdmin" ObjectId="@Model.Id.ToString()" Type="CommentType.CommentVote" />

    }
    else
    {
        <CnGalWebSite.Components.Progressings.ProgressingCard Page />

    }
}

<CnGalWebSite.Shared.MasaComponent.Shared.Components.TrackEvent DataType="TrackEventDataType.Vote" EventType="TrackEventType.View" ObjectId="@Model.Id.ToString()"
                                                                ObjectName="@Model.Name" />


@code {
    [Parameter]
    public string Id { get; set; }

    public string MainPageHtml { get; set; }
    public int currentPage { get; set; } = 1;
    public string NoticeCard { get; set; } = "";
    public string CurrentUserRank { get; set; }
    bool isReady = false;
    bool isNotFound = false;
    bool isLoading = false;
    bool isFirstLoad = true;

    public VoteViewModel Model { get; set; } = new VoteViewModel();

    public PagedResultDto<CommentViewModel> ListComments = new PagedResultDto<CommentViewModel> { Data = new List<CommentViewModel>(), CurrentPage = 1, TotalCount = 0 };
    public bool IsAdmin { get; set; } = false;
    string LastLookName = "";
    bool isFrist = true;
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }


    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            NavigationManager.LocationChanged -= LocationChanged;
            NavigationManager.LocationChanged += LocationChanged;
            isFirstLoad = false;
        }
    }

    protected override async Task OnInitializedAsync()
    {
        await Refresh();
    }

    public async Task Refresh()
    {
        try
        {
            //获取周边信息
            Model = await _dataCatcheService.VoteIndexPageCatche.GetCache(Id);
            //判断投票名称是否为空 为空则跳转到主页
            if (string.IsNullOrWhiteSpace(Model.Name))
            {
                NavigationManager.NavigateTo("/votes/home");
            }

            isReady = true;

            var user = await authenticationStateTask;
            if (user.User.Identity.IsAuthenticated)
            {
                IsAdmin = user.User.IsInRole("Editor");
            }
            else
            {
                _dataCatcheService.VoteIndexPageCatche.Clean(Id);
            }
        }
        catch (Exception exc)
        {
            isReady = true;
            isNotFound = true;
            StateHasChanged();
        }

    }

    public async Task OnVoted()
    {
        _dataCatcheService.VoteIndexPageCatche.Clean(Id);
        Model = await _dataCatcheService.VoteIndexPageCatche.GetCache(Id);
        StateHasChanged();
    }
    public async Task OnReVoted()
    {
        Model.ShowResult = false;
        StateHasChanged();
    }

    public void HiddenStateChanged()
    {
        Model.IsHidden = !Model.IsHidden;
        StateHasChanged();

    }
    public async void LocationChanged(object sender, LocationChangedEventArgs args)
    {
        if (Id != Model.Id.ToString())
        {
            if (_dataCatcheService.VideoIndexPageCatche.Check(Id) == false)
            {
                isLoading = true;
                StateHasChanged();
                await Refresh();
                isLoading = false;
                StateHasChanged();
            }
            else
            {
                await Refresh();
                StateHasChanged();
            }

        }
    }

    #region 释放实例

    public void Dispose()
    {

        NavigationManager.LocationChanged -= LocationChanged;

        GC.SuppressFinalize(this);
    }
    #endregion
}
